package com.whstudio.common.pattern;

import java.util.Vector;

public abstract class Subject implements Observable {

	private boolean changed = false;
	private Vector<Subscriber> subscribers;

	/** Construct an Observable with zero Observers. */

	public Subject() {
		subscribers = new Vector<Subscriber>();
	}

	@Override
	public synchronized void addObserver(Subscriber o) {
		if (o == null)
			throw new NullPointerException();
		if (!subscribers.contains(o)) {
			subscribers.addElement(o);
		}
	}

	@Override
	public synchronized void clearChanged() {
		changed = false;
	}

	@Override
	public synchronized int countObservers() {
		return subscribers.size();
	}

	@Override
	public synchronized void deleteObserver(Subscriber o) {
		subscribers.removeElement(o);
	}

	@Override
	public synchronized void deleteObservers() {
		subscribers.removeAllElements();
	}

	@Override
	public synchronized boolean hasChanged() {
		return changed;
	}

	@Override
	public void notifyObservers() {
		notifyObservers(null);
	}

	@Override
	public void notifyObservers(Object arg) {
		Subscriber[] arrLocal;
		synchronized (this) {
			if (!changed)
				return;
			arrLocal = subscribers.toArray(new Subscriber[this.countObservers()]);
			clearChanged();
		}

		for (int i = arrLocal.length - 1; i >= 0; i--)
			arrLocal[i].update(this, arg);
	}
	
	

	@Override
	public synchronized void setChanged() {
		changed = true;
	}
	
	@Override
	public Vector<Subscriber> getSubscribers() {
		return subscribers;
	}
	
}
